﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json.Linq;
using ST.Buz.Base.Entity;
using ST.Buz.Base.Enums;
using ST.Buz.Base.ViewModel;
using ST.Buz.Service;
using ST.Common.Util;
using ST.Common.Util.Model;
using ST.Common.Util.Mvc;
using ST.Common.Util.Text;
using System;
using System.Net;

namespace ST.Buz.Web.Controllers
{
	[Route("sys/log")]
	public class Sys_LogController : MyBaseController
	{
		private readonly IServiceSysLog service;
		private readonly IServiceSysAttachment serviceSysAttachment;
		private VM_RelatedModule[] relatedModules;

		public Sys_LogController(IServiceSysLog _service,
			IServiceSysAttachment _serviceSysAttachment,
			ILogger<Sys_LogController> _logger
		) : base(_logger)
		{
			service = _service;

			serviceSysAttachment = _serviceSysAttachment;
			relatedModules = new VM_RelatedModule[]{
				new VM_RelatedModule(){
					id="sys_attachment",
					name="相关附件",
					count=0
				}
			};
		}

		private VMS_Sys_Log GetSearchModelFromJson(JObject paras)
		{
			var vm = new VMS_Sys_Log();
			vm.pnum = TextHelper.GetInt(paras, "pnum");
			vm.psize = TextHelper.GetInt(paras, "psize");
			vm.sortorder = TextHelper.GetString(paras, "sortorder");

			vm.content = TextHelper.GetString(paras, "content");
			vm.srcurl = TextHelper.GetString(paras, "srcurl");
			vm.level = TextHelper.GetIntNullable(paras, "level");
			vm.logman = TextHelper.GetString(paras, "logman");
			vm.logmanid = TextHelper.GetIntNullable(paras, "logmanid");
			vm.logmanip = TextHelper.GetString(paras, "logmanip");
			vm.moduleid = TextHelper.GetIntNullable(paras, "moduleid");
			vm.modulename = TextHelper.GetString(paras, "modulename");
			vm.modulecode = TextHelper.GetString(paras, "modulecode");
			vm.serviceid = TextHelper.GetIntNullable(paras, "serviceid");
			vm.servicename = TextHelper.GetString(paras, "servicename");
			vm.servicecode = TextHelper.GetString(paras, "servicecode");
			vm.actionid = TextHelper.GetIntNullable(paras, "actionid");
			vm.actionname = TextHelper.GetString(paras, "actionname");
			vm.actioncode = TextHelper.GetString(paras, "actioncode");
			vm.date_s = TextHelper.GetDateTimeStart(paras, "date_s");
			vm.date_e = TextHelper.GetDateTimeEnd(paras, "date_e");
			vm.ids = TextHelper.GetInts(paras, "ids");
			return vm;
		}

		private VMS_Sys_Log GetSearchModelFromGetRequest()
		{
			var vm = new VMS_Sys_Log();
			vm.pnum = TextHelper.GetInt(Request.Query["pnum"]);
			vm.psize = TextHelper.GetInt(Request.Query["psize"]);
			vm.sortorder = TextHelper.GetString(Request.Query["sortorder"]);

			vm.content = TextHelper.GetString(Request.Query["content"]);
			vm.srcurl = TextHelper.GetString(Request.Query["srcurl"]);
			vm.level = TextHelper.GetIntNullable(Request.Query["level"]);
			vm.logman = TextHelper.GetString(Request.Query["logman"]);
			vm.logmanid = TextHelper.GetIntNullable(Request.Query["logmanid"]);
			vm.logmanip = TextHelper.GetString(Request.Query["logmanip"]);
			vm.moduleid = TextHelper.GetIntNullable(Request.Query["moduleid"]);
			vm.modulename = TextHelper.GetString(Request.Query["modulename"]);
			vm.modulecode = TextHelper.GetString(Request.Query["modulecode"]);
			vm.serviceid = TextHelper.GetIntNullable(Request.Query["serviceid"]);
			vm.servicename = TextHelper.GetString(Request.Query["servicename"]);
			vm.servicecode = TextHelper.GetString(Request.Query["servicecode"]);
			vm.actionid = TextHelper.GetIntNullable(Request.Query["actionid"]);
			vm.actionname = TextHelper.GetString(Request.Query["actionname"]);
			vm.actioncode = TextHelper.GetString(Request.Query["actioncode"]);
			vm.date_s = TextHelper.GetDateTimeStart(Request.Query["date_s"]);
			vm.date_e = TextHelper.GetDateTimeEnd(Request.Query["date_e"]);
			vm.ids = TextHelper.GetInts(Request.Query["ids"]);
			return vm;
		}

		private VMS_Sys_Log GetSearchModelFromPostRequest()
		{
			var vm = new VMS_Sys_Log();
			vm.pnum = TextHelper.GetInt(Request.Form["pnum"]);
			vm.psize = TextHelper.GetInt(Request.Form["psize"]);
			vm.sortorder = TextHelper.GetString(Request.Form["sortorder"]);

			vm.content = TextHelper.GetString(Request.Form["content"]);
			vm.srcurl = TextHelper.GetString(Request.Form["srcurl"]);
			vm.level = TextHelper.GetIntNullable(Request.Form["level"]);
			vm.logman = TextHelper.GetString(Request.Form["logman"]);
			vm.logmanid = TextHelper.GetIntNullable(Request.Form["logmanid"]);
			vm.logmanip = TextHelper.GetString(Request.Form["logmanip"]);
			vm.moduleid = TextHelper.GetIntNullable(Request.Form["moduleid"]);
			vm.modulename = TextHelper.GetString(Request.Form["modulename"]);
			vm.modulecode = TextHelper.GetString(Request.Form["modulecode"]);
			vm.serviceid = TextHelper.GetIntNullable(Request.Form["serviceid"]);
			vm.servicename = TextHelper.GetString(Request.Form["servicename"]);
			vm.servicecode = TextHelper.GetString(Request.Form["servicecode"]);
			vm.actionid = TextHelper.GetIntNullable(Request.Form["actionid"]);
			vm.actionname = TextHelper.GetString(Request.Form["actionname"]);
			vm.actioncode = TextHelper.GetString(Request.Form["actioncode"]);
			vm.date_s = TextHelper.GetDateTimeStart(Request.Form["date_s"]);
			vm.date_e = TextHelper.GetDateTimeEnd(Request.Form["date_e"]);
			vm.ids = TextHelper.GetInts(Request.Form["ids[]"]);
			return vm;
		}

		public IActionResult Index()
		{
			return RedirectToAction("List");
		}

		[ValidateSession]
		[HttpGet("list")]
		public IActionResult List()
		{
			ViewBag.ServiceCode = "591A8CA013";
			ViewBag.LogLevelOptions = GetEnums(typeof(Microsoft.Extensions.Logging.LogLevel));
			return View();
		}

		[HttpPost("search")]
		public IActionResult Search([FromBody]JObject paras)
		{
			try
			{
				UserSession sessionCurrent = GetSessionFromRequest();
				var searchModel = GetSearchModelFromJson(paras);
				PageData pageData = service.GetPageList(searchModel);

				return new JsonResultPage(pageData);
			}
			catch (AuthException ex)
			{
				return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.Unauthorized);
			}
			catch (BuzException ex)
			{
				return new JsonResultBase(false, ex.Message);
			}
			catch (ArgumentException ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.BadRequest);
			}
			catch (Exception ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				return new JsonResultBase(false, "请求出错", (int)HttpStatusCode.InternalServerError);
			}
		}

		/// <summary>
		/// 获取指定角色信息
		/// </summary>
		/// <returns></returns>
		[ValidateSession]
		[HttpGet("view/{id}")]
		[HttpGet("view")]
		public IActionResult ViewDetail(string id)
		{
			ViewBag.ServiceCode = "591A8CA013";
			ViewBag.RelatedModules = relatedModules;
			try
			{
				int rowID = TextHelper.GetInt(id);

				UserSession sessionCurrent = GetSessionFromRequest();

				var vm = service.GetViewDetail(rowID, sessionCurrent);
				return View("View", vm);
			}
			catch (AuthException ex)
			{
				return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.Unauthorized);
			}
			catch (BuzException ex)
			{
				return new JsonResultBase(false, ex.Message);
			}
			catch (ArgumentException ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.BadRequest);
			}
			catch (Exception ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				return new JsonResultBase(false, "请求出错", (int)HttpStatusCode.InternalServerError);
			}
		}

		/// <summary>
		/// 获取查看时的角色信息
		/// </summary>
		/// <returns></returns>
		[ValidateSession]
		[HttpPost("detail")]
		public IActionResult ViewJson([FromBody]JObject paras)
		{
			try
			{
				CheckParams();

				int id = TextHelper.GetInt(paras, "id");

				UserSession sessionCurrent = GetSessionFromRequest();
				var model = service.GetViewDetail(id, sessionCurrent);

				if (model == null)
				{
					return new JsonResultBase(false, "未找到相关记录", (int)HttpStatusCode.NotFound);
				}

				return new JsonResultBase(model);
			}
			catch (AuthException ex)
			{
				return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.Unauthorized);
			}
			catch (BuzException ex)
			{
				return new JsonResultBase(false, ex.Message);
			}
			catch (ArgumentException ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.BadRequest);
			}
			catch (Exception ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				return new JsonResultBase(false, "请求出错", (int)HttpStatusCode.InternalServerError);
			}
		}

		[ValidateSession]
		[HttpPost("delete")]
		public IActionResult Delete([FromBody]JObject paras)
		{
			try
			{
				CheckParams();

				UserSession sessionCurrent = GetSessionFromRequest();
				var rowID = TextHelper.GetInt(paras, "id");
				var result = service.Delete(rowID, sessionCurrent);

				return new JsonResultBase(result);
			}
			catch (AuthException ex)
			{
				return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.Unauthorized);
			}
			catch (BuzException ex)
			{
				return new JsonResultBase(false, ex.Message);
			}
			catch (ArgumentException ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.BadRequest);
			}
			catch (Exception ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				return new JsonResultBase(false, "删除失败", (int)HttpStatusCode.InternalServerError);
			}
		}

		[ValidateSession]
		[HttpPost("batchdelete")]
		public IActionResult BatchDelete([FromBody]int[] ids)
		{
			try
			{
				CheckParams();

				UserSession sessionCurrent = GetSessionFromRequest();

				var result = service.BatchDelete(ids, sessionCurrent);

				return new JsonResultBase(result);
			}
			catch (AuthException ex)
			{
				return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.Unauthorized);
			}
			catch (BuzException ex)
			{
				return new JsonResultBase(false, ex.Message);
			}
			catch (ArgumentException ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.BadRequest);
			}
			catch (Exception ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				return new JsonResultBase(false, "删除失败", (int)HttpStatusCode.InternalServerError);
			}
		}

		[ValidateSession]
		[HttpPost("clear")]
		public IActionResult Clear([FromBody]JObject paras)
		{
			try
			{
				CheckParams();

				UserSession sessionCurrent = GetSessionFromRequest();
				var result = service.Clear(sessionCurrent);

				return new JsonResultBase(result);
			}
			catch (AuthException ex)
			{
				return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.Unauthorized);
			}
			catch (BuzException ex)
			{
				return new JsonResultBase(false, ex.Message);
			}
			catch (ArgumentException ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				return new JsonResultBase(false, ex.Message, (int)HttpStatusCode.BadRequest);
			}
			catch (Exception ex)
			{
				logger.LogError(ex.InnerException ?? ex, ex.Message);
				return new JsonResultBase(false, "删除失败", (int)HttpStatusCode.InternalServerError);
			}
		}

		[HttpPost("export")]
		public IActionResult Export(JObject obj)
		{
			//context.Response.ContentType = "application/vnd.ms-excel";
			//context.Response.Charset = "UTF-8";
			//context.Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");
			//context.Response.AppendHeader("Content-Disposition", string.Format("attachment;filename={0}_{1}.xls", HttpUtility.UrlEncode(Title), DateTime.Now.ToString("yyyyMMdd_HHmmss")));
			//switch (context.Request.QueryString["all"])
			//return File(byte)
			throw new NotImplementedException();
		}
	}
}